//
//  MainViewController.m
//  OCMicroBlog
//
//  Created by 002 on 15/11/4.
//  Copyright © 2015年 002. All rights reserved.
//

#import "MainViewController.h"
#import "HomeTableTableView.h"
#import "MessageTableViewController.h"
#import "DiscoverTableViewController.h"
#import "ProfileTableViewController.h"
#import "UIButton+Extention.h"
#import "UIView+Extention.h"

@interface MainViewController ()

/**
 *  撰写按钮
 */
@property(nonatomic,strong) UIButton *composedButton;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 添加子控制器
    [self addChildViewControllers];
    
    // 设置 ‘拽写’ 按钮
    [self setupComposedButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    

}

#pragma mark - 视图生命周期
/**
 *  视图即将显示
 *
 *  @param animated 是否动画
 */
- (void)viewWillAppear:(BOOL)animated {
    // 必须先调用父类的方法
    [super viewWillAppear:true];
    
    [self.tabBar bringSubviewToFront:self.composedButton];
    
}

/**
 *  添加所有子控制器
 */
- (void)addChildViewControllers {
    [self addChildVC:[[HomeTableTableView alloc] init] WithTitle:@"首页" imageName:@"tabbar_home"];
    [self addChildVC:[[MessageTableViewController alloc] init] WithTitle:@"消息" imageName:@"tabbar_message_center"];
    [self addChildViewController:[UIViewController new]];
    [self addChildVC:[[DiscoverTableViewController alloc] init] WithTitle:@"发现" imageName:@"tabbar_discover"];
    [self addChildVC:[[ProfileTableViewController alloc] init] WithTitle:@"我" imageName:@"tabbar_profile"];
}

/**
 *  添加子控制器
 *
 *  @param VC        子控制器
 *  @param title     子控制器名称
 *  @param imageName iamgename
 */
- (void)addChildVC:(UIViewController *)VC WithTitle:(NSString *) title imageName:(NSString *)imageName {
    
    VC.title = title;
    
    [VC.tabBarItem setImage:[UIImage imageNamed:imageName]];
    
    UINavigationController *nVC = [[UINavigationController alloc] initWithRootViewController:VC];
    
    [self addChildViewController:nVC];

}

/**
 *  设置 ‘拽写’ 按钮
 */
- (void)setupComposedButton {
    [self.tabBar addSubview:self.composedButton];

    // 1. 设置 ‘ 拽写按钮’ 位置
    NSInteger count = self.childViewControllers.count;
    // 每个tabbarItem的宽度 ‘-1’ 为了保证‘拽写按钮’能完全被点击到
    CGFloat width = self.view.width / count -1;
    self.composedButton.frame = CGRectInset(self.tabBar.bounds, 2 * width, 0);
    
    // 2. 添加监听方法
    [self.composedButton addTarget:self action:@selector(clickComposedButton) forControlEvents:UIControlEventTouchUpInside];
    
}

/**
 *  拽写按钮点击
 */
- (void)clickComposedButton {
    NSLog(@"点击了拽写按钮");
}

#pragma mark - 懒加载控件
/**
 *  懒加载控件
 */
- (UIButton *)composedButton {
    if (_composedButton == nil) {
        _composedButton = [UIButton initWithImageName:@"tabbar_compose_icon_add" BackImageName:@"tabbar_compose_button"];
    }
    return _composedButton;
}

@end
